package com.xdjk.networkdemo.net;

import android.app.Activity;
import android.app.ProgressDialog;

import com.orhanobut.logger.Logger;
import com.xdjk.networkdemo.listener.LoadingDialogListener;
import com.xdjk.networkdemo.utils.DialogUtils;

import rx.Subscriber;

/**
 * 上传文件的RxJava2回调
 */

public abstract class UploadOCallBack<T> extends Subscriber<T> implements LoadingDialogListener {
    private ProgressDialog progressDialog;
    private Activity mActivity;
    public UploadOCallBack(Activity activity) {
        this.mActivity = activity;
        progressDialog = DialogUtils.createProgressDialog(activity, "", "文件上传中...");
    }

    @Override
    public void onStart() {
        super.onStart();
        showLoading();
    }

    @Override
    public void onNext(T t) {
        onUpLoadSuccess(t);
    }

    @Override
    public void onError(Throwable e) {
        hideLoading();
        onUpLoadFail(e);
    }

    @Override
    public void onCompleted() {
        hideLoading();
    }
    //监听进度的改变
    public void onProgressChange(long bytesWritten, long contentLength) {
        int progress = (int) (bytesWritten * 100 / contentLength);
        Logger.d("上传进度=" + progress);
        if (null != progressDialog) {
            progressDialog.setProgress(progress);
        }
    }

    //上传成功的回调
    public abstract void onUpLoadSuccess(T t);

    //上传失败回调
    public abstract void onUpLoadFail(Throwable e);

    @Override
    public void showLoading() {
        if (!mActivity.isFinishing()) {
            progressDialog.show();
        }
    }

    @Override
    public void hideLoading() {
        progressDialog.hide();
    }
}
